/*
* 收料单材料列表
* */

import 'dart:convert';

import 'package:center_beijing/api/material_science_api.dart';
import 'package:center_beijing/common/logutil.dart';
import 'package:center_beijing/common/notification.dart';
import 'package:center_beijing/common/styles.dart';
import 'package:center_beijing/common/utils.dart';
import 'package:center_beijing/config/global_config.dart';
import 'package:center_beijing/config/routeConfig.dart';
import 'package:center_beijing/widgets/custom_loading_widget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

class MaterialWarehousingDetailList extends StatefulWidget {
  @override
  _MaterialWarehousingDetailListState createState() => _MaterialWarehousingDetailListState();
}

class _MaterialWarehousingDetailListState extends State<MaterialWarehousingDetailList> with SingleTickerProviderStateMixin {

  EasyRefreshController _controller = EasyRefreshController();
  CustomLoading loading = CustomLoading.withMessage('提交中...');
  var receive = Get.arguments;
  List dataSource = [];
  int page = 1;
  int pageSize = 15;
  bool firstLoad = true;
  @override
  void initState() {
    super.initState();
    bus.on('refreshReceiveDetailList', (arg) {
      page = 1;
      this.getAllReceived();
    });
  }

  @override
  void dispose() {
    _controller.dispose();
    bus.off('refreshReceiveDetailList');
    super.dispose();
  }

  /*
  * 获取收料单材料列表
  * */
  getAllReceived() async {
    var pass = {
      'queryFields': json.encode([{
        "columnName": 'receiptGenid',
        "dataType": "string",
        "operator": "=",
        "queryValue": receive['id'],
      }]),
      'page': page,
      'limit': pageSize,
    };
    var result = await getReceivedMaterialEntryExList(pass);
    if (this.page == 1) {
      dataSource.clear();
    }
    firstLoad = false;
    if (result != null&&result['hasError']==null) {
      this.setState(() {
        if (result['results'].length == 0) {
          _controller.finishLoad(success: true, noMore: true);
        } else {
          dataSource.addAll(result['results']);
          if(dataSource.length==result['totalRecordNum']){
            _controller.finishLoad(success: true, noMore: true);
          }
        }
      });
    }else{
      _controller.finishLoad(success: true);
    }

  }

  /*
  * 删除收料单详情
  * */
  deleteMaterialDetail(value) async {
    loading.show(delay: 30);
    var result = await deleteReceivedSheetDetail({'id': value['id']});
    loading.dismiss();
    if (result != null&& result['hasError'] == null) {
      Fluttertoast.showToast(msg: '删除成功');
      page = 1;
      this.getAllReceived();
    }
    LogUtil.d(result);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('收料单材料'),
        ),
        body: Container(
          color: Styles.MainBackgroundColor,
          padding:
          EdgeInsets.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom+70),
          child: NotificationListener(
            onNotification: (_) {
              FocusScope.of(context).requestFocus(new FocusNode());
              return false;
            },
            child: EasyRefresh.custom(
                shrinkWrap: true,
                firstRefresh: true,
                controller: _controller,
                header: MaterialHeader(),
                footer: ClassicalFooter(
                    loadingText: '加载中',
                    loadText: '上拉加载',
                    noMoreText: '没有更多数据',
                    loadedText: '加载完成',
                    infoText: '更新于 %T',
                    textColor: Styles.NoMoreColor,
                    showInfo: false),
                emptyWidget: (dataSource.length == 0 && !firstLoad)
                    ? Center(
                  child: Image(
                    image: AssetImage('assets/images/no_data.png'),
                    width: 128,
                    height: 150,
                  ),
                )
                    : null,
                onRefresh: () async {
                  _controller.finishLoad(success: true, noMore: false);
                  if (mounted) {
                    page = 1;
                    this.getAllReceived();
                  }
                },
                onLoad: () async {
                  await Future.delayed(Duration(seconds: 2), () {
                    if (mounted) {
                      page++;
                      this.getAllReceived();
                    }
                  });
                },
                slivers: <Widget>[
                  SliverList(
                    delegate: SliverChildBuilderDelegate(
                          (context, index) {
                        return Column(
                          children: [
                            GestureDetector(
                              onTap: () {
Get.toNamed(RouteConfig.materialWarehousingDetail,arguments: this.dataSource[index]);
                              },
                              child: Container(
                                alignment: Alignment.centerLeft,
                                color: Colors.white,
                                margin: EdgeInsets.fromLTRB(
                                    0, Styles.spacing8, 0, 0),
                                padding: EdgeInsets.fromLTRB(
                                    Styles.spacing12,
                                    Styles.spacing8,
                                    Styles.spacing12,
                                    Styles.spacing8),
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    Container(
                                      margin: EdgeInsets.fromLTRB(
                                          0, Styles.spacing4, 0, Styles.spacing4),
                                      child: Text('规格型号  ${this.dataSource[index]['specName']}',style: TextStyle(color: Styles.DetailColor,fontSize: Styles.NormalFont),),
                                    ),
                                    Container(
                                      margin: EdgeInsets.fromLTRB(
                                          0, Styles.spacing4, 0, Styles.spacing4),
                                      child: Text('数       量  ${this.dataSource[index]['quantity']['value']}',style: TextStyle(color: Styles.DetailColor,fontSize: Styles.NormalFont),),
                                    ),
                                    Container(
                                      margin: EdgeInsets.fromLTRB(
                                          0, Styles.spacing4, 0, Styles.spacing4),
                                      child: Text('计量单位  ${this.dataSource[index]['measureUnit']}',style: TextStyle(color: Styles.DetailColor,fontSize: Styles.NormalFont),),
                                    ),
                                    Container(
                                      margin: EdgeInsets.fromLTRB(
                                          0, Styles.spacing4, 0, Styles.spacing4),
                                      child: Text('供货合同  ${this.dataSource[index]['contractNumber']}',style: TextStyle(color: Styles.DetailColor,fontSize: Styles.NormalFont),),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                            GestureDetector(
                              onTap: () {
                                FocusScope.of(context).requestFocus(new FocusNode());
                                showDialog(
                                    barrierDismissible: false,
                                    context: this.context,
                                    builder:
                                        (BuildContext context) {
                                      return AlertDialog(
                                        title: Text('注意'),
                                        content: Text('确认删除吗？'),
                                        actions: <Widget>[
                                          new Container(
                                            child: FlatButton(
                                              child: new Text(
                                                "取消",
                                                style: TextStyle(
                                                    color: Colors
                                                        .black),
                                              ),
                                              onPressed: () {
                                                Navigator.pop(
                                                    context);
                                              },
                                            ),
                                          ),
                                          new Container(
                                            child: FlatButton(
                                              child: new Text(
                                                "确定",
                                                style: TextStyle(
                                                    color: Colors
                                                        .red),
                                              ),
                                              onPressed: () {
                                                Navigator.pop(
                                                    context);
                                                this.deleteMaterialDetail(
                                                    this.dataSource[index]);
                                              },
                                            ),
                                          ),
                                        ],
                                      );
                                    });

                              },
                              child: Container(
                                padding:
                                EdgeInsets.all(Styles.spacing16),
                                decoration: BoxDecoration(
                                    border: Border(top: BorderSide(color: Styles.LineColor,width: 1)),color: Colors.white),
                                alignment: Alignment.center,
                                child: Text(
                                  '删除',
                                  style: TextStyle(
                                      color: Styles.DetailColor,
                                      fontSize: Styles.NormalFont),
                                ),
                              ),
                            )
                          ],
                        );
                      },
                      childCount: dataSource.length,
                    ),
                  ),
                ]),
          ),
        ),
        floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
        floatingActionButton: Container(
          padding: EdgeInsets.fromLTRB(
              Styles.spacing8, Styles.spacing8, Styles.spacing8, 10),
          child: Container(
            decoration: new BoxDecoration(
              //背景
              color: Styles.BlueColor,
              //设置四周圆角 角度
              borderRadius: BorderRadius.all(Radius.circular(12.0)),
            ),
            child: FlatButton(
              disabledColor: Styles.SelectColor,
              onPressed: () {
                Get.toNamed(RouteConfig.addMaterialDetailWarehousing,arguments: receive);
              },
              child: Container(
                height: Styles.MainButtonHeight,
                alignment: Alignment.center,
                child: Text(
                  '添加材料',
                  style: TextStyle(
                      fontSize: Styles.MainButtonTextFont, color: Colors.white),
                ),
              ),
            ),
          ),
        )
    );
  }
}
